﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using HSHLogicLayer;
using HSHLogicLayer.DataWS;
using iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Data;
using System.Text.RegularExpressions;

namespace HSHLogicLayer
{
    public class PDFHelper
    {
        string m_TempPath= Environment.GetFolderPath(Environment.SpecialFolder.InternetCache) + @"\";
        public PDFHelper()
        {
        }

        //public string CreatePDF_old(DSRakazim pdfds)
        //{
        //    string path = @"C:\Users\Sagiv\DEV\newPDF.pdf";
        //    Document Doc = new Document(PageSize.A4, 20, 20, 20, 20);
        //    PdfWriter writer = PdfWriter.GetInstance(Doc, new FileStream(path, FileMode.Create));
        //    Doc.Open();
        //    Doc.Close();

        //    return path;
        //}

        public string CreatePDF(DSRakazim dt, string EventName)
        {
            string badJuri = dt.GetRakazimToEvent[0]["jurisdiction"].ToString().Trim();
            string regex = String.Format("[{0}]", Regex.Escape(new string(Path.GetInvalidFileNameChars())));
            Regex removeInvalidChars = new Regex(regex, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.CultureInvariant);
            string juri = removeInvalidChars.Replace(badJuri, "");
            string fixEventName= removeInvalidChars.Replace(EventName,"");
            string outpath = juri+"_"+fixEventName+".pdf";
            string bodypath = CreatePDFBody(dt,EventName);
            PdfReader reader = new PdfReader(bodypath);
            PdfReader s_reader;
            if (((string)dt.GetRakazimToEvent[0]["PaymentTypeName"]) == "משקי הקיבוצים")
            {
                s_reader = new PdfReader(HSHLogicLayer.Properties.Resources.MishkeyTemplate);
            }
            else
            {
                s_reader = new PdfReader(HSHLogicLayer.Properties.Resources.KibbutzTemplate);
            }
            FileStream fs = new FileStream(outpath, FileMode.Create);
            PdfStamper stamper = new PdfStamper(reader,fs);
            PdfImportedPage page = stamper.GetImportedPage(s_reader, 1);
            int n = reader.NumberOfPages;
            PdfContentByte Background;
            for (int i = 1; i <= n; i++)
            {
                Background = stamper.GetUnderContent(i);
                Background.AddTemplate(page, 0, 0);
            }

            stamper.Close();
            fs.Close();
            File.Delete(bodypath);
            return outpath;
        }

        public String CreatePDFBody(DSRakazim dt, string EventName)
        {
            Document Doc = new Document(PageSize.A4, 40, 40, 120, 300);
            string Path = "BodyPDF.pdf";
            PdfWriter writer = PdfWriter.GetInstance(Doc, new FileStream(Path, FileMode.Create));
            Doc.Open();
            PdfContentByte cb = writer.DirectContent;
            BaseFont bf = BaseFont.CreateFont(
                    @".\Resources\DAVID.TTF", "Identity-H", true);
            iTextSharp.text.Font f1 = new iTextSharp.text.Font(bf, 9, iTextSharp.text.Font.NORMAL);
            iTextSharp.text.Font f2 = new iTextSharp.text.Font(bf, 14, iTextSharp.text.Font.NORMAL);
            iTextSharp.text.Font f3 = new iTextSharp.text.Font(bf, 24, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
            iTextSharp.text.Font f4 = new iTextSharp.text.Font(bf, 36, iTextSharp.text.Font.NORMAL, BaseColor.BLUE);
            PdfPTable introduction = new PdfPTable(1);
            introduction.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
            PdfPCell cell = new PdfPCell(new Phrase("טופס התחייבות להשתתפות באירוע", f3));
            cell.Border = iTextSharp.text.Rectangle.NO_BORDER;
            cell.HorizontalAlignment = Element.ALIGN_CENTER;
            introduction.AddCell(cell);
            introduction.CompleteRow();
            cell = new PdfPCell(new Phrase(("אני, "+dt.GetRakazimToEvent[0]["FirstName"]+" "+ dt.GetRakazimToEvent[0]["LastName"]+
                                            ", רכז החינוך ב"+dt.GetRakazimToEvent[0]["jurisdiction"].ToString().Trim()+", מאשר בזאת את השתתפותם של החניכים ב"+EventName+", כמפורט להלן: "),f2));
            cell.Border = iTextSharp.text.Rectangle.NO_BORDER;
            cell.HorizontalAlignment = Element.ALIGN_LEFT;
            introduction.AddCell(cell);
            introduction.CompleteRow();
            cell = new PdfPCell(new Phrase((" "), f2));
            cell.Border = iTextSharp.text.Rectangle.NO_BORDER;
            cell.HorizontalAlignment = Element.ALIGN_LEFT;
            introduction.AddCell(cell);
            introduction.CompleteRow();
            PdfPTable Details = new PdfPTable(7);
            Details.SetWidths(new float[] { 30f, 10f, 6f, 8f, 9f, 10f, 4f });
            Details.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
            cell = new PdfPCell(new Phrase("מס'", f1));
            cell.GrayFill = (0.8f);
            Details.AddCell(cell);
            cell = new PdfPCell(new Phrase("שם החניך", f1));
            cell.GrayFill = (0.8f);
            Details.AddCell(cell);
            cell = new PdfPCell(new Phrase("טלפון", f1));
            cell.GrayFill = (0.8f);
            Details.AddCell(cell);
            cell = new PdfPCell(new Phrase("ת.ז.", f1));
            cell.GrayFill = (0.8f);
            Details.AddCell(cell);
            cell = new PdfPCell(new Phrase("סכום", f1));
            cell.GrayFill = (0.8f);
            Details.AddCell(cell);
            cell = new PdfPCell(new Phrase("שם הורה מאשר", f1));
            cell.GrayFill = (0.8f);
            Details.AddCell(cell);
            cell = new PdfPCell(new Phrase("הערות", f1));
            cell.GrayFill = (0.8f);
            Details.AddCell(cell);
            //for (int i = 0; i < dt.GetRakazPeopleInEvent.Columns.Count; i++)
            //{
            //    cell = new PdfPCell(new Phrase((String)dt.GetRakazPeopleInEvent.Columns[i].Caption, f1));
            //    cell.GrayFill = (0.8f);
            //    Details.AddCell(cell);
            //}

            for (int i = 0; i < dt.GetRakazPeopleInEvent.Rows.Count; i++)
            {
                f1.SetStyle(iTextSharp.text.Font.UNDERLINE);
                cell = new PdfPCell(new Phrase(Convert.ToString(i + 1), f1));
                Details.AddCell(cell);

                f1.SetStyle(iTextSharp.text.Font.NORMAL);
                
                    cell = new PdfPCell(new Phrase((Convert.ToString(dt.GetRakazPeopleInEvent.Rows[i]["FirstName"]))+" "+(Convert.ToString(dt.GetRakazPeopleInEvent.Rows[i]["LastName"])),f1));
                    Details.AddCell(cell);
                    cell = new PdfPCell(new Phrase(Convert.ToString(dt.GetRakazPeopleInEvent.Rows[i]["Phone"]),f1));
                    Details.AddCell(cell);
                    cell = new PdfPCell(new Phrase(Convert.ToString(dt.GetRakazPeopleInEvent.Rows[i]["IsraelID"]),f1));
                    Details.AddCell(cell);
                    cell = new PdfPCell(new Phrase(Convert.ToString(dt.GetRakazPeopleInEvent.Rows[i]["Payment"]),f1));
                    Details.AddCell(cell);
                    cell = new PdfPCell(new Phrase((Convert.ToString(dt.GetRakazPeopleInEvent.Rows[i]["ParentFirstName"]))+" "+(Convert.ToString(dt.GetRakazPeopleInEvent.Rows[i]["ParentLastName"])),f1));
                    Details.AddCell(cell);
                    string bd = "";
                    if (!string.IsNullOrEmpty(dt.GetRakazPeopleInEvent.Rows[i]["IsBrotherDiscount"].ToString()))
                    {
                        if (Convert.ToBoolean(dt.GetRakazPeopleInEvent.Rows[i]["IsBrotherDiscount"]))
                            bd = ",הנחת אחים";
                    }
                    cell = new PdfPCell(new Phrase((Convert.ToString(dt.GetRakazPeopleInEvent.Rows[i]["EventComments"]))+" "+bd,f1));;
                    Details.AddCell(cell);   
                
                Details.CompleteRow();
            }
            Doc.Add(introduction);
            Doc.Add(Details);
            PdfPTable footer = new PdfPTable(1);

            Doc.Close();

            return Path;
        }

        public byte[] blobPDF(string filePath)
        {
            FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
            BinaryReader br = new BinaryReader(fs);

            byte[] BlobPDF = br.ReadBytes((int)fs.Length);

            br.Close();
            fs.Close();

            return BlobPDF;
        }

        public bool unBlobPDF(byte[] PDFByteArray,string path)
        {
            FileStream fs = new FileStream(path,
                                    FileMode.Create, FileAccess.Write);
            BinaryWriter bw = new BinaryWriter(fs);
            bw.Write(PDFByteArray);
            fs.Close();
            return true;
        }

        public string StampChangesOnPDF(string oldPath)
        {
            string newPath = oldPath + "1";
            FileStream fs = new FileStream(newPath, FileMode.Create, FileAccess.Write);
            byte[] PDFBA = new byte[0];
            PdfReader reader = new PdfReader(oldPath);
            PdfStamper stamper = new PdfStamper(reader, fs);
            int n = reader.NumberOfPages;
            BaseFont bf = BaseFont.CreateFont(
                    @".\Resources\DAVID.TTF", "Identity-H", true);
            iTextSharp.text.Font f1 = new iTextSharp.text.Font(bf, 11, iTextSharp.text.Font.BOLD);
            string approvedby ="תינופלט ורשואש םייוניש ליכמ ספוטה";


            for (int i = 1; i <= n; i++)
            {
                PdfContentByte pdfPageContents = stamper.GetOverContent(i);
                pdfPageContents.SetColorFill(BaseColor.WHITE);
                pdfPageContents.MoveTo(50, 160);
                pdfPageContents.LineTo(PageSize.A4.Width - 50, 160);
                pdfPageContents.LineTo(PageSize.A4.Width - 50, 140);
                pdfPageContents.LineTo(50, 140);
                pdfPageContents.Fill();
                pdfPageContents.SetColorFill(BaseColor.BLACK);
                ColumnText.ShowTextAligned(pdfPageContents, PdfContentByte.ALIGN_CENTER, new Phrase(approvedby, f1), PageSize.A4.Width / 2, 150, 0);

                //pdfPageContents.BeginText();
                //pdfPageContents.SetFontAndSize(bf, 12);
                //pdfPageContents.SetColorFill(BaseColor.BLACK);

                //pdfPageContents.ShowTextAligned(PdfContentByte.ALIGN_CENTER, approved, PageSize.A4.Width / 2, 150, 0);
                //pdfPageContents.EndText();
            }
            stamper.FormFlattening = true;
            stamper.Close();
            fs.Close();
            File.Delete(oldPath);
            return newPath;
        }

        public void MergeFiles(string destinationFile, string[] sourceFiles)
        {
            try
            {
                int f = 0;
                // we create a reader for a certain document
                PdfReader reader = new PdfReader(sourceFiles[f]);
                // we retrieve the total number of pages
                int n = reader.NumberOfPages;
                //Console.WriteLine("There are " + n + " pages in the original file.");
                // step 1: creation of a document-object
                Document document = new Document(reader.GetPageSizeWithRotation(1));
                // step 2: we create a writer that listens to the document
                PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));
                // step 3: we open the document
                document.Open();
                PdfContentByte cb = writer.DirectContent;
                PdfImportedPage page;
                int rotation;
                // step 4: we add content
                while (f < sourceFiles.Length)
                {
                    int i = 0;
                    while (i < n)
                    {
                        i++;
                        document.SetPageSize(reader.GetPageSizeWithRotation(i));
                        document.NewPage();
                        page = writer.GetImportedPage(reader, i);
                        rotation = reader.GetPageRotation(i);
                        if (rotation == 90 || rotation == 270)
                        {
                            cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                        }
                        else
                        {
                            cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                        }
                        //Console.WriteLine("Processed page " + i);
                    }
                    f++;
                    if (f < sourceFiles.Length)
                    {
                        reader = new PdfReader(sourceFiles[f]);
                        // we retrieve the total number of pages
                        n = reader.NumberOfPages;
                        //Console.WriteLine("There are " + n + " pages in the original file.");
                    }
                }
                // step 5: we close the document
                document.Close();
            }
            catch (Exception e)
            {
                string strOb = e.Message;
            }
        }

        public int CountPageNo(string strFileName)
        {
            // we create a reader for a certain document
            PdfReader reader = new PdfReader(strFileName);
            // we retrieve the total number of pages
            return reader.NumberOfPages;
        }
    }
}
